package com.sdx.payment.wxpay;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sdx.common.utils.Signature;
import com.sdx.common.utils.Utils;
import com.sdx.console.transaction.entity.FinTransaction;
import com.sdx.payment.RefundResult;
import com.sdx.payment.service.IPaymentService;
import com.sdx.payment.system.entity.CfgThirdRecord;
import com.sdx.payment.system.service.CfgThirdRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @ClassName WxpayService
 * @Description: 微信支付服务类
 * @author: tanbaocai
 * @date: 2018/9/26 17:26
 */
@Service
public class WxpayService implements IPaymentService {
	@Value("${base.domain}${server.servlet.context-path}")
	private String notifyUrl;

//	@Value("${wx.transfer.mchid}")

	private static final String notifyPrefix = "trans/refund/";
	private static final String notifyPostfix = "/notify.do";

	@Value("${wxpay.certpath}")
	private String certPath;

	@Autowired
	private CfgThirdRecordService cfgThirdRecordService;

	/**
	 *
	 * @param refundId 退款单id
	 * @param refundMoney 退款金额
	 * @param transaction 原交易单
	 * @return
	 */
	@Override
	public RefundResult refund(String refundId,int refundMoney, FinTransaction transaction) {
		RefundResult result = new RefundResult();
		try {
			WxPayConfig payConfig = getWxPayConfig(transaction.getMerchantId());
			RefundRequest request = new RefundRequest();
			request.setAppid(payConfig.getAppId());
			request.setMch_id(payConfig.getMchId());
			request.setNonce_str(Utils.getRandomStringByLength(32));
			request.setNotify_url(notifyUrl+notifyPrefix+refundId+notifyPostfix);
			request.setOut_refund_no(refundId);
			request.setRefund_fee(refundMoney);
			request.setOut_trade_no(transaction.getTransactionId());
			request.setTotal_fee(transaction.getTotalMoney().intValue());
			String sign = Signature.getSign(request,payConfig.getKey());
			request.setSign(sign);
			String certFile = certPath+payConfig.getMchId()+"/apiclient_cert.p12";
			RefundResponse response = WxpayAPI.refund(request,payConfig.getMchId(),certFile);
			if (response.isSuccess()) {
				result.setResultCode(1);
			} else {
				result.setResultCode(0);
				result.setMessage(response.getMessage());
			}
		} catch (IOException e) {
			e.printStackTrace();
			result.setResultCode(0);
			result.setMessage("获取微信配置失败["+transaction.getMerchantId()+"]，"+e.getMessage());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			result.setResultCode(0);
			result.setMessage("微信生成签字失败["+transaction.getMerchantId()+"]，"+e.getMessage());
		}
		return result;
	}
	public WxPayConfig getWxPayConfig(String mchid) throws IOException {
		CfgThirdRecord id = new CfgThirdRecord();
		id.setPlatformType("wxpay");
		id.setUnid(mchid);
		CfgThirdRecord cfgThirdRecord = cfgThirdRecordService.queryById(id);
		ObjectMapper mapper = new ObjectMapper();
		WxPayConfig result = mapper.readValue(cfgThirdRecord.getConfigJson(), WxPayConfig.class);
		return result;
	}
}
